package controllers

import (
	"encoding/xml"
	"fmt"
	"github.com/astaxie/beego"
	"net/url"
	"xianzhi/service"
	"xianzhi/utils"
	"xianzhi/utils/wechat"
)

type MyTestController struct {
	beego.Controller
}

func (c *MyTestController) Prepare() {
	c.EnableXSRF = false;
}

func (c *MyTestController) Index() {
	/*wechat.SendOrderNotice("oqLSUxBAClxUs1h4GUdlmzaJOxB4", "您有新的订单", "", "",
		time.Now().Format("2006-01-02 15:04:05"), "勾选学校", "张小明 15968562356", "选择套餐", "基础A")*/
	id := c.GetString("id")
	p := map[string]interface{}{}
	p["id"] = id
	order := service.GetOrderInfo(p)
	if order.Id > 0 {
		p = map[string]interface{}{}
		p["orderId"] = order.Id
		service.DelOrderSchool(p)
		service.DelOrderPushTime(p)
		p = map[string]interface{}{}
		p["id"] = order.Id
		service.DelOrder(p)
	}
	c.Ctx.WriteString("ok")
}

func (c *MyTestController) TestXml() {
	var res *utils.ResJsonStruct
	var p wechat.EventMsg
	if err := xml.Unmarshal(c.Ctx.Input.RequestBody, &p); err != nil {
		res = utils.ResJson(0, "解析失败", err.Error())
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	fmt.Printf("ToUserName：%s FromUserName：%s CreateTime：%d MsgType：%s Event：%s EventKey：%s Ticket：%s\n",
		p.ToUserName, p.FromUserName, p.CreateTime, p.MsgType, p.Event, p.EventKey, p.Ticket)
	res = utils.ResJson(0, "解析成功", p)
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *MyTestController) InitAdminUser() {
	var input url.Values
	var p map[string]interface{}

	input = url.Values{
		"name": {"超级管理员"},
		"describe": {"超级管理员"},
	}
	roleId, _ := service.AddUserAdminRole(input)

	p = map[string]interface{}{}
	p["account"] = "admin"
	record := service.GetUserAdminInfo(p)
	if record.Id > 0 {
		c.Ctx.WriteString("请不要重复初始化管理员")
		return
	}

	input = url.Values{
		"role_id": {fmt.Sprintf("%d", roleId)},
		"account": {"admin"},
		"password": {"xianzhi123!@"},
		"status": {"1"},
	}
	service.AddUserAdmin(input)

	c.Ctx.WriteString("管理员初始化成功，登录名：admin 密码:xianzhi123!@")
}

func (c *MyTestController) AccessToken() {
	t := wechat.GetAccessToken("xianzhi")
	c.Ctx.WriteString(t)
}
